class GeoController < ApplicationController
  layout "general"
  
  def index
    @provinces = Area.roots
  end
  
  def show
    @area = Area.find(params[:id])
    @map = GMap.new("map_div")
    @map.control_init(:large_map => true,:map_type => Variable.new("G_HYBRID_MAP"))
    @map.center_zoom_init([@area.lat,@area.lng], @area.zoom)
  end
  
  # for xhr, return areas list
  def list
    if params[:id].blank?
      @areas = Area.roots
    else
      @parent = Area.find(params[:id])
      @areas = @parent.children
    end
  end
  
  # for xhr, return areas and schools list
  def schools_list
    if params[:id].blank?
      @areas = Area.roots
    else
      @parent = Area.find(params[:id])
      logger.info("PARENT CHILDREN: #{@parent.children}")
      @areas = @parent.children
      if @areas.empty?
        @schools = School.find :all, :conditions => "area_id=#{params[:id]}"
      end
    end
  end
  
  # for xhr, select school for tour
  def school_select
  end
  
  # GET search what you want do go, and list all schools in the area result
  def search
    redirect_to home_url if params[:q].blank?
    query_result = Area.find(:all, :conditions => Area.conditions_by_like(params[:q], 'title'))
    @areas = query_result.collect{|a| a.all_children}.flatten!.uniq!
    logger.info(@areas.inspect)
    @schools = []
    @areas.each do |area|
      next if area.all_children.blank?
      all_children = area.all_children
      @schools[area.id] = School.find(:all, :conditions => "area_id in (#{all_children.collect{|s| s.id }.join(', ')})")
    end
    logger.info(@schools.inspect)
    respond_to do |format|
      format.html
    end
  end
  
  private
  def generate
    Province.find(:all).each do |province|
      parent = Area.new(:title => province.title)
      parent.save
      
      province.cities.each do |city|
        child1 = Area.new(:title => city.title)
        child1.save
        child1.move_to_child_of parent
        
        city.counties.each do |county|
          child2 = Area.new(:title => county.title)
          child2.save
          child2.move_to_child_of child1
        end
      end
    end
  end
end
